package com.ming.reggie.controller;

import com.ming.reggie.common.R;
import com.ming.reggie.entity.Employee;
import com.ming.reggie.entity.Page;
import com.ming.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired(required = false)
    private EmployeeService employeeService;

    @Autowired(required = false)
    public HttpSession session;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee){
        R<Employee> r = employeeService.login(employee);

        //判断请求是否成功
        if(r.getCode() == 1){
            session.setAttribute("employee",r.getData().getId());
        }

        return r;
    }

    @RequestMapping("/logout")
    public R<String> logout(){
        session.invalidate();

        return R.success("退出成功");
    }

    @PostMapping
    public R<String> insert(@RequestBody Employee employee){
        Long empId = (Long) session.getAttribute("employee");
        //添加创建人
        employee.setCreateUser(empId);
        //添加修改人
        employee.setUpdateUser(empId);

        employeeService.InsertEmployee(employee);
        return R.success("添加成功");

    }

    @RequestMapping("/page")
    public R<Page<Employee>> findByName(Integer page,Integer pageSize,String name){
        Page<Employee> PageObj = employeeService.findByPage(page, pageSize, name);
        return R.success(PageObj);
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Long id){
        Employee employee = employeeService.findById(id);
        return R.success(employee);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee){
        Long employeeId = (Long) session.getAttribute("employee");
        employee.setUpdateUser(employeeId);
        employeeService.update(employee);
        return R.success("修改成功");
    }
}
